package com.seu.algorithms.string;

import java.util.*;

/**
 * @author liangfeihu
 * @since 2019/2/22
 */
public class StrCountAndSort {
    public static void main(String args[]) {
        String str = "hfdjkslahfkjoiefsjkarwerfdsf";
        Map<Character, KeyValue> map = new HashMap<Character, KeyValue>();

        char c;
        KeyValue kv = null;
        for (int i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            kv = map.get(c);
            if (kv == null) {
                kv = new KeyValue();
                kv.ch = c;
                kv.count = 1;
                map.put(c, kv);
            } else {
                kv.count++;
            }
        }

        List<KeyValue> list = new ArrayList<KeyValue>(map.values());

        // 方法1
        Collections.sort(list);
        // 方法2
        Collections.sort(list, new Comparator<KeyValue>() {
            @Override
            public int compare(KeyValue o1, KeyValue o2) {
                return o2.count - o1.count;
            }
        });

        for (KeyValue o : list) {
            System.out.println(o.ch + " " + o.count);
        }

        System.out.println("------------------------");
        countAndSort();
        System.out.println("------------------------");

        int[] array1 = {1,2,3,4,3,2};
        int[] copyArray = Arrays.copyOf(array1, array1.length);
        System.out.println(Arrays.toString(copyArray));

    }

    private static void countAndSort() {
        String str = "abdfklvdaadcc";
        Map<Character, Integer> map = new HashMap<>();
        Character temp = null;
        for (int j = 0; j < str.length(); j++) {
            temp = str.charAt(j);
            if (map.containsKey(temp)) {
                map.put(temp, map.get(temp) + 1);
            } else {
                map.put(temp, 1);
            }
        }

        TreeSet<KeyValue> treeSet = new TreeSet<>();
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
            treeSet.add(new KeyValue(entry.getKey(), entry.getValue()));
        }

        System.out.println("---------------------------");

        Iterator<KeyValue> iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            KeyValue next = iterator.next();
            System.out.println(next.ch + " " + next.count);
        }
    }

}
